#include "sendfile.h"

#include <QByteArray>
#include <QFile>
#include <QFileInfo>

sendfile::sendfile(QObject *parent)
    : QObject{parent}
{

}

void sendfile::connectServer(unsigned short port, QString ip)
{
    m_tcp = new QTcpSocket;
    m_tcp->connectToHost(QHostAddress(ip) , port);
    connect( m_tcp , &QTcpSocket::connected , this , &sendfile::connectOK);
    connect(m_tcp , &QTcpSocket::disconnected  , this ,[=](){
        m_tcp->close();
        m_tcp->deleteLater();
        emit gameover();
    });
}

void sendfile::SendFile(QString path)
{
    QFile file(path);
    QFileInfo info(path);
    int file_size = info.size();
    file.open(QFile::ReadOnly);

    while(!file.atEnd()){
        static int num = 0;
        if(num == 0){
            m_tcp->write((char*)&file_size , 4);
        }
        QByteArray line = file.readLine();
        num+=line .size();
        int percent = num*100/file_size;
        emit current_percent(percent);

        m_tcp->write(line);
    }
}
